package com.umeox.watch.moto.contact.receiver;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;

import com.umeox.moto.watch.themes.util.UToast;
import com.umeox.watch.moto.contact.ui.SinglePTTActivity;
import com.umeox.watch.moto.contact.ui.IncomingCallActivity;
import com.umeox.watch.moto.contact.ui.OutgoingCallActivity;
import com.umeox.watch.moto.dataservice.DataProvider;


/**
 * Created by Rambo 3/25/21
 * Describe:
 */
public class PushToTalkReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (!DataProvider.isActivated()) {
            UToast.show("The device has not been bound. Please bind it before using this function", Toast.LENGTH_LONG);
            return;
        }

        if (isActivityTop(SinglePTTActivity.class, context)
                || isActivityTop(IncomingCallActivity.class,context)
                || isActivityTop(OutgoingCallActivity.class,context)
                || DataProvider.inForbidPeriodNow()
            /*|| isActivityTop(ContactsActivity.class, context)*/) {
            return;
        }

        //启动联系人选择界面
        Uri uri = Uri.parse("contact://view/" + "PTT_CHOOSE_CONTACT");
        Intent pttIntent = new Intent("com.wherecom.intent.action.CHOOSE_CONTACT", uri);
        pttIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(pttIntent);
    }

    /**
     * 判断某activity是否处于栈顶
     *
     * @return true在栈顶 false不在栈顶
     */
    private boolean isActivityTop(Class cls, Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(cls.getName());
    }
}
